
<template>
  <div class="route-optimization-container">
    <div class="page-header">
      <div class="header-title">
        <h2>路线优化</h2>
        <span class="subtitle">智能规划最优配送路线</span>
      </div>
      <div class="header-actions">
        <el-button-group>
          <el-button type="primary" @click="startOptimization" :loading="optimizing">
            <el-icon><Position /></el-icon>开始优化
          </el-button>
          <el-button @click="resetForm">
            <el-icon><RefreshLeft /></el-icon>重置
          </el-button>
        </el-button-group>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：参数设置 -->
      <el-col :span="8">
        <el-card class="config-card">
          <template #header>
            <div class="card-header">
              <span>优化参数</span>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="optimizationForm"
            :rules="formRules"
            label-position="top"
          >
            <!-- 优化目标 -->
            <el-form-item label="优化目标" prop="objective">
              <el-select v-model="optimizationForm.objective" class="w-full">
                <el-option label="最短距离" value="distance" />
                <el-option label="最短时间" value="time" />
                <el-option label="最低成本" value="cost" />
                <el-option label="综合优化" value="comprehensive" />
              </el-select>
            </el-form-item>

            <!-- 算法选择 -->
            <el-form-item label="优化算法" prop="algorithm">
              <el-select v-model="optimizationForm.algorithm" class="w-full">
                <el-option label="遗传算法" value="genetic" />
                <el-option label="蚁群算法" value="ant_colony" />
                <el-option label="模拟退火" value="simulated_annealing" />
              </el-select>
            </el-form-item>

            <!-- 车辆限制 -->
            <el-form-item label="车辆数量" prop="vehicleCount">
              <el-input-number 
                v-model="optimizationForm.vehicleCount"
                :min="1"
                :max="100"
                class="w-full"
              />
            </el-form-item>

            <!-- 时间窗口 -->
            <el-form-item label="配送时间窗口">
              <el-time-picker
                v-model="optimizationForm.timeWindow"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                class="w-full"
              />
            </el-form-item>

            <!-- 高级选项 -->
            <el-collapse v-model="activeCollapse">
              <el-collapse-item title="高级选项" name="advanced">
                <el-form-item label="负载平衡">
                  <el-switch v-model="optimizationForm.loadBalancing" />
                </el-form-item>
                
                <el-form-item label="考虑交通状况">
                  <el-switch v-model="optimizationForm.considerTraffic" />
                </el-form-item>
                
                <el-form-item label="优先级配送">
                  <el-switch v-model="optimizationForm.priorityDelivery" />
                </el-form-item>
                
                <el-form-item label="算法迭代次数" v-if="optimizationForm.algorithm !== 'simulated_annealing'">
                  <el-slider
                    v-model="optimizationForm.iterations"
                    :min="100"
                    :max="1000"
                    :step="100"
                    show-stops
                  />
                </el-form-item>
              </el-collapse-item>
            </el-collapse>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：地图和结果 -->
      <el-col :span="16">
        <!-- 地图显示 -->
        <el-card class="map-card">
          <template #header>
            <div class="card-header">
              <span>路线规划</span>
              <div class="map-controls">
                <el-radio-group v-model="mapMode" size="small">
                  <el-radio-button label="edit">编辑模式</el-radio-button>
                  <el-radio-button label="preview">预览模式</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>

          <div class="map-container">
            <!-- 实际应用中这里会集成地图组件 -->
            <div class="map-placeholder">
              <el-empty description="地图加载中...">
                <template #image>
                  <el-icon style="font-size: 60px"><Location /></el-icon>
                </template>
              </el-empty>
            </div>
          </div>
        </el-card>

        <!-- 优化结果 -->
        <el-card v-if="optimizationResult" class="result-card">
          <template #header>
            <div class="card-header">
              <span>优化结果</span>
              <el-button-group>
                <el-button type="success" size="small" @click="applyOptimization">
                  应用方案
                </el-button>
                <el-button type="primary" size="small" @click="exportResult">
                  导出方案
                </el-button>
              </el-button-group>
            </div>
          </template>

          <el-tabs v-model="activeResultTab">
            <el-tab-pane label="概览" name="overview">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="优化目标">{{ getObjectiveText() }}</el-descriptions-item>
                <el-descriptions-item label="使用算法">{{ getAlgorithmText() }}</el-descriptions-item>
                <el-descriptions-item label="总距离">{{ optimizationResult.totalDistance }}km</el-descriptions-item>
                <el-descriptions-item label="总时间">{{ optimizationResult.totalTime }}小时</el-descriptions-item>
                <el-descriptions-item label="总成本">¥{{ optimizationResult.totalCost }}</el-descriptions-item>
                <el-descriptions-item label="车辆数量">{{ optimizationResult.vehicleCount }}辆</el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>

            <el-tab-pane label="详细路线" name="routes">
              <el-table :data="optimizationResult.routes" stripe>
                <el-table-column prop="vehicleId" label="车辆" width="100" />
                <el-table-column prop="route" label="配送路线" show-overflow-tooltip />
                <el-table-column prop="distance" label="距离(km)" width="100" />
                <el-table-column prop="time" label="时间(h)" width="100" />
                <el-table-column prop="load" label="载重率" width="100">
                  <template #default="{ row }">
                    <el-progress :percentage="row.load" />
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Position,
  RefreshLeft,
  Location
} from '@element-plus/icons-vue'

// 表单引用
const formRef = ref(null)

// 优化表单数据
const optimizationForm = reactive({
  objective: 'comprehensive',
  algorithm: 'genetic',
  vehicleCount: 5,
  timeWindow: [new Date(2025, 2, 14, 8, 0), new Date(2025, 2, 14, 18, 0)],
  loadBalancing: true,
  considerTraffic: true,
  priorityDelivery: false,
  iterations: 500
})

// 表单验证规则
const formRules = {
  objective: [
    { required: true, message: '请选择优化目标', trigger: 'change' }
  ],
  algorithm: [
    { required: true, message: '请选择优化算法', trigger: 'change' }
  ],
  vehicleCount: [
    { required: true, message: '请输入车辆数量', trigger: 'blur' }
  ]
}

// 高级选项展开状态
const activeCollapse = ref(['advanced'])

// 地图模式
const mapMode = ref('edit')

// 优化状态
const optimizing = ref(false)

// 优化结果
const optimizationResult = ref(null)

// 结果标签页
const activeResultTab = ref('overview')

// 获取优化目标文本
const getObjectiveText = () => {
  const objectiveMap = {
    distance: '最短距离',
    time: '最短时间',
    cost: '最低成本',
    comprehensive: '综合优化'
  }
  return objectiveMap[optimizationForm.objective]
}

// 获取算法文本
const getAlgorithmText = () => {
  const algorithmMap = {
    genetic: '遗传算法',
    ant_colony: '蚁群算法',
    simulated_annealing: '模拟退火'
  }
  return algorithmMap[optimizationForm.algorithm]
}

// 开始优化
const startOptimization = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    optimizing.value = true
    
    // 模拟优化过程
    setTimeout(() => {
      // 实际应用中这里应该调用后端API进行路线优化
      optimizationResult.value = {
        totalDistance: 456.7,
        totalTime: 8.5,
        totalCost: 3456.8,
        vehicleCount: optimizationForm.vehicleCount,
        routes: [
          {
            vehicleId: 'V001',
            route: '仓库 → 配送点A → 配送点B → 配送点C → 仓库',
            distance: 156.2,
            time: 2.8,
            load: 85
          },
          {
            vehicleId: 'V002',
            route: '仓库 → 配送点D → 配送点E → 仓库',
            distance: 98.5,
            time: 1.9,
            load: 65
          }
          // 更多路线...
        ]
      }
      
      optimizing.value = false
      
      ElMessage.success('路线优化完成！')
    }, 2000)
    
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  
  ElMessageBox.confirm(
    '确定要重置所有优化参数吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    formRef.value.resetFields()
    optimizationResult.value = null
    ElMessage.success('已重置所有参数')
  }).catch(() => {})
}

// 应用优化方案
const applyOptimization = () => {
  ElMessage.success('优化方案已应用到调度计划')
}

// 导出优化结果
const exportResult = () => {
  ElMessage.success('优化方案已导出')
}
</script>

<style scoped>
.route-optimization-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-card,
.map-card,
.result-card {
  margin-bottom: 20px;
}

.map-container {
  height: 400px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.map-placeholder {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.map-controls {
  display: flex;
  gap: 12px;
}

.w-full {
  width: 100%;
}

:deep(.el-collapse-item__header) {
  font-size: 14px;
  color: #606266;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}
</style>